<template>
<div>
    <my-bread level1="权限管理" level2="角色列表"></my-bread>
    <el-card>
        <!-- 添加角色按钮区域 -->
        <el-row>
            <el-col>
                <el-button type="primary" @click="showAddUser">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 角色列表区域 -->
        <el-table :data="roleList" border stripe>
            <!-- 展开列 -->
            <el-table-column type='expand'>
                <template slot-scope="scope">
                    <el-row v-for="(item1,index) in scope.row.children" :key="index" class="expand-row">
                        <el-col :span="5">
                            <el-tag closable @close="deleRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <el-row v-for="(item2,index) in item1.children" :key="index">
                                <el-col :span="6">
                                    <el-tag closable type="success" @close="deleRight(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag type="warning" closable v-for="(item3,index) in item2.children" :key="index" @close="deleRight(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                    <span v-if="scope.row.children.length===0">未分配权限</span>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type='index'>
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称">
            </el-table-column>
            <el-table-column prop="roleDesc" label="角色描述">
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template slot-scope="scop">
                    <el-row>
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRightDia(scop.row.id)"></el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoleById(scop.row.id)"></el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDia(scop.row)"></el-button>
                    </el-row>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体 -->
            <el-form :model="addUserForm" ref="addUserFormRef" :rules="addRoleFormRules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addUserForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addUserForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改权限的对话框 -->
        <el-dialog title="修改权限" :visible.sync="dialogFormVisibleRight">
            <!-- 树形结构 -->
            <el-tree ref="tree" :data="treeList" show-checkbox node-key="id" default-expand-all :default-checked-keys="arrcheck" :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleRight = false">取 消</el-button>
                <el-button type="primary" @click="setRoleRight">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="40%" @close="addRoleDialogClosed">
            <el-form :model="editRoleForm" ref="editRoleFormRef" :rules="editRoleFormRules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoles">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
</div>
</template>

<script>
export default {
    data() {
        return {
            // 所有角色列表数据
            roleList: [],
            // 添加用户
            addDialogVisible: false,
            // 修改权限
            dialogFormVisibleRight: false,
            treeList: null,
            defaultProps: {
                label: 'authName',
                children: 'children'
            },
            arrcheck: [],
            roleId: 0,
            // 添加用户表单
            addUserForm: {},
            //   添加角色表单验证
            addRoleFormRules: {
                roleName: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }],
                roleDesc: [{
                    required: true,
                    message: '请输入角色描述',
                    trigger: 'blur'
                }]
            },
            // 编辑用户表单
            editRoleForm: {},
            editRoleDialogVisible: false,
            // 编辑用户表单验证
            editRoleFormRules: {
                roleName: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }],
                roleDesc: [{
                    required: true,
                    message: '请输入角色描述',
                    trigger: 'blur'
                }]
            },
        }
    },
    mounted() {
        this.getRoleList()
    },
    methods: {
        //获取角色列表
        async getRoleList() {
            const res = await this.$http.get(`roles`)
            const {
                data,
                meta: {
                    status,
                    msg
                }
            } = res.data
            if (status !== 200) {
                return this.$message.warning(msg)
            }
            this.roleList = data
        },
        // 显示添加用户对话框
        showAddUser() {
            this.addDialogVisible = true
        },
        //添加用户
        async addUser() {
            const res = await this.$http.post('roles', this.addUserForm)
            console.log(res);
            const {
                meta: {
                    msg,
                    status
                }
            } = res.data
            if (status !== 200) return this.$message.warning(msg)
            this.getRoleList()
        },
        // 添加角色对话框的关闭
        addDialogClosed() {
            this.$refs.addUserFormRef.resetFields()
        },
        //显示编辑角色对话框
        async showEditRightDia(id) {
            this.editRoleDialogVisible = true
            const {
                data: res
            } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) return this.$message.error('查询角色信息失败！')
            this.editRoleForm = res.data
        },
        //编辑角色
        async editRoles() {
            const res = await this.$http.put('roles/' + this.editRoleForm.roleId, {
                roleName: this.editRoleForm.roleName,
                roleDesc: this.editRoleForm.roleDesc
            })
            const {
                meta: {
                    msg,
                    status
                }
            } = res.data
            if (status !== 200) {
                return this.$message.warning(msg)
            }
            this.getRoleList()
            this.editRoleDialogVisible = false
        },
        //编辑角色对话框关闭
        addRoleDialogClosed() {
            this.$refs.editRoleFormRef.resetFields()
        },
        // 删除角色
        async removeRoleById(id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该角色, 是否继续?',
                '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const {
                data: res
            } = await this.$http.delete('roles/' + id)
            if (res.meta.status !== 200) return this.$message.error('删除角色失败！')
            this.$message.success('删除用户成功！')
            this.getRoleList()
        },
        //修改权限-发送请求
        async setRoleRight(roleId) {
            const keys = [
                ...this.$refs.tree.getCheckedKeys(),
                ...this.$refs.tree.getHalfCheckedKeys()
            ]
            console.log(keys);
            // join() 方法用于把数组中的所有元素放入一个字符串
            const idStr = keys.join(',')
            const res = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: idStr
            })
            const {
                meta: {
                    status
                }
            } = res.data
            if (status !== 200) {
                return this.$message.error("分配权限失败")
            }
            this.$message.success('分配权限成功!')
            this.getRoleList()
            this.dialogFormVisibleRight = false
        },
        //设置权限-打开对话框
        async showSetRightDia(role) {
            this.roleId = role.id
            //   递归获取三级节点的id
            this.getLeafkeys(role, this.arrcheck)
            this.dialogFormVisibleRight = true
            //获取树形结构的权限数据
            const res = await this.$http.get(`rights/tree`)
            const {
                data,
                meta: {
                    status
                }
            } = res.data
            if (status === 200) {
                this.treeList = data
            }
        },
        // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
        getLeafkeys(node, arr) {
            // 没有children属性，则是三级节点
            if (!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item => this.getLeafkeys(item, arr))
        },
        //取消权限
        async deleRight(role, rightId) {
            const res = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            const {
                data,
                meta: {
                    status,
                    msg
                }
            } = res.data
            if (status === 200) {
                this.$message.success(msg)
                role.children = data
            }
        }
    }
}
</script>

<style scoped>
.el-card {
    margin-top: 20px;
}

.expand-row {
    padding: 0 50px;
}

.el-table {
    margin-top: 20px;
}
</style>
